from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from myapp.Ser import *


class TeacherM(APIView):
    def post(self, request):
        ser = TeacherSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})

    def get(self, request):
        data = Teacher.objects.all()
        all_data = TeacherSer(data, many=True)
        return Response(all_data.data)


class Tlogin(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        if username and password:
            teacher = Teacher.objects.filter(username=username, password=password).first()
            if teacher:
                return Response({'code': 200, 'tid': teacher.id, 'tname': teacher.username})
        else:
            return Response({'code': 10010})


class StudentM(APIView):
    def post(self, request):
        ser = StudentSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})

    def get(self, request):
        tid = request.GET.get('tid')
        if tid:
            stu = Tstu.objects.filter(teacher_id=tid).all()
            ser = StudentSer(stu, many=True)
            return Response({'list': ser.data})
        else:
            stu = Tstu.objects.filter(teacher_id__isnull=True).all()
            ser = StudentSer(stu, many=True)
            return Response({'list': ser.data})

    def put(self, request):
        id = request.GET.get('id')
        tid = request.GET.get('tid')
        if tid:
            Tstu.objects.filter(id=id).update(teacher_id=tid)
        else:
            Tstu.objects.filter(id=id).update(teacher_id='')
            return Response({'code': 200})
